package com.example.exercise;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author: dangwen
 * @createDate: 2021/6/17
 */
public class ProducerAndConsumer03 {

    private final static int MAX = 20;
    private final static int MIN = 0;

    static BlockingQueue<Integer> bq = new ArrayBlockingQueue<>(20);


    static class Gun{
         void input(){
//        while (bq.size() >= MAX){
            try {
                bq.put(1);
                System.out.println(bq.size() == MAX ? "枪膛已满" : "填入了一颗子弹："+bq.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//        }
        }

         void output(){
            try {
                bq.take();
                System.out.println(bq.size() == MIN ? "枪膛已空" : "射出了一颗子弹："+bq.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Producer implements Runnable{
        private Gun gun;
        public Producer(Gun gun){
            this.gun = gun;
        }

        @Override
        public void run() {
            while (true){
                gun.input();
            }
        }
    }

    public static class Consumer implements Runnable{

        private Gun gun;

        public Consumer(Gun gun){
            this.gun = gun;
        }

        @Override
        public void run() {
            while (true){
                gun.output();
            }
        }
    }

    public static void main(String[] args) {
        Gun gun = new Gun();
        new Thread(new Producer(gun)).start();
        new Thread(new Consumer(gun)).start();
    }
}
